package cn.learn.async.unsafe;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * @author huangyezhan
 * @version 1.0
 * @date 2021年05月30日18:57
 */
public class UnsafeBank {

    public static void main(String[] args) {
        Account account  = new Account(100, "育儿基金");
        Drawing drawing1 = new Drawing(account, 50, "小孩零花");
        Drawing drawing2 = new Drawing(account, 100, "小孩上学");

        drawing1.start();
        drawing2.start();
    }

}

@Getter
@Setter
@AllArgsConstructor
class Account {

    private int    money;
    private String name;

}

class Drawing extends Thread {
    // 账户
    private final Account account;
    // 取了多少钱
    private int     drawingMoney;
    // 现在取出到手里有多少钱
    private int     nowMoney;

    /**
     * @param threadName 线程名称
     */
    public Drawing(Account account, int drawingMoney, String threadName) {
        super(threadName);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        synchronized (account){
            if (account.getMoney() - drawingMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "钱不够了，取不了了！");
                return;
            }
            // 模拟延时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            account.setMoney(account.getMoney() - drawingMoney);
            nowMoney = nowMoney + drawingMoney;

            System.out.println(this.getName() + "：" + nowMoney);
            System.out.println(account.getName() + "余额为：" + account.getMoney());
        }
    }

}
